package com.ocom.ugcapi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.dto.GetMealTimeDto;
import com.ocom.common.entity.card.EntityXfGoodListOrg;
import com.ocom.common.entity.card.EntityXfMealInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.payconfig.EntityDishesInfo;
import com.ocom.common.enums.OpTypeDiffEnum;
import com.ocom.common.enums.OpTypeEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.GetDishesInfoDetailListRequest;
import com.ocom.common.request.payconfig.mealorder.GetOrderDishesRequest;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.FeeRefundRequest;
import com.ocom.common.request.payhandle.GetRecordProcessRequest;
import com.ocom.common.request.ugcapi.GzhAppNameVo;
import com.ocom.common.request.ugcapi.OrderReturnRequest;
import com.ocom.common.request.ugcapi.OrderedShowRequest;
import com.ocom.common.request.web.ConsTimeConfigOnShowRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.ugcapi.client.PayConfigClientService;
import com.ocom.ugcapi.client.PayHandleClientService;
import com.ocom.ugcapi.client.XfRecodeClientService;
import com.ocom.ugcapi.vo.OrderedShowDishesListVo;
import com.ocom.ugcapi.vo.OrderedShowVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/5/15
 **/
@RestController
public class OrderPageController {


    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    XfRecodeClientService xfRecodeClientService;

    @Autowired
    PayHandleClientService payHandleClientService;

    /**
     * 6.5已点餐查询（OrderPage/orderedShow）
     */
    @PostMapping(WxServiceUrl.URL_OrderPageOrderedShow)
    public Result orderedShow(@RequestBody Map<String, Object> map) {
        OrderedShowRequest request = JSON.parseObject(JSON.toJSONString(map), OrderedShowRequest.class);

        OrderedShowVo orderedShowVo = new OrderedShowVo();
        Long comId = request.getUserInfo().getComId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("comId", comId);
        jsonObject.put("orderNo", request.getOrderNo());
        jsonObject.put("size", 1);
        jsonObject.put("page", 0);

        try {
            Result consumeDetail = xfRecodeClientService.getConsumeDetail(jsonObject);
            if (200 != consumeDetail.getCode()) {
                return consumeDetail;
            }
            Map<String, Object> consumeDetailData = JSON.parseObject(JSON.toJSONString(consumeDetail.getData()), HashMap.class);
            List<EntityXfRecord> xfRecordlist = JSON.parseArray(JSON.toJSONString(consumeDetailData.get("list")), EntityXfRecord.class);
            EntityXfRecord entityXfRecord = xfRecordlist.get(0);
            orderedShowVo.setOpType(OpTypeEnum.getName(entityXfRecord.getOpType().intValue()));
            orderedShowVo.setOpTypeDiff(OpTypeDiffEnum.getName(entityXfRecord.getOpTypeDiff().intValue()));
            orderedShowVo.setDiscount(entityXfRecord.getDiscount());
            orderedShowVo.setConsMoney(entityXfRecord.getConsMoney());
            orderedShowVo.setRealMoney(entityXfRecord.getRealMoney());
            Result mealNameInfo = payConfigClientService.getMealNameInfo(request.getUserInfo().getComId(), entityXfRecord.getMealNo());
            if (200 != mealNameInfo.getCode()) {
                return mealNameInfo;
            }
            Map<String, Object> mealNameInfoData = JSON.parseObject(JSON.toJSONString(mealNameInfo.getData()), HashMap.class);
            List<EntityXfMealInfo> entityXfMealInfos = JSON.parseArray(JSON.toJSONString(mealNameInfoData.get("list")), EntityXfMealInfo.class);

            OrderedShowRequest orderedShowRequest = new OrderedShowRequest();
            orderedShowRequest.setOrderNo(request.getOrderNo());
            orderedShowRequest.setMonthValue(request.getMonthValue());
            orderedShowRequest.setComId(comId);
            Result resultOrderDishesDetail = xfRecodeClientService.getOrderDishesDetail(orderedShowRequest);
            if (200 != resultOrderDishesDetail.getCode()) {
                return resultOrderDishesDetail;
            }
            List<OrderedShowDishesListVo> dishesList = JSON.parseArray(JSON.toJSONString(resultOrderDishesDetail.getData()), OrderedShowDishesListVo.class);

            List<Integer> dishesIds = dishesList.stream().map(OrderedShowDishesListVo -> OrderedShowDishesListVo.getDishesId()).collect(Collectors.toList());
            GetDishesInfoDetailListRequest getDishesInfoRequest = new GetDishesInfoDetailListRequest();
            getDishesInfoRequest.setComId(comId);
            getDishesInfoRequest.setDishesIds(dishesIds);

            if(dishesIds!=null && dishesIds.size() > 0){
                Result getDishesInfoResult = payConfigClientService.findByComIdAndDishesId(getDishesInfoRequest);
                if (200 != getDishesInfoResult.getCode()) {
                    return getDishesInfoResult;
                }
                List<EntityDishesInfo> dishesInfos = JSON.parseArray(JSON.toJSONString(getDishesInfoResult.getData()), EntityDishesInfo.class);
                Map<Integer, EntityDishesInfo> dishesMap = dishesInfos.stream().collect(Collectors.toMap(EntityDishesInfo::getDishesId, EntityDishesInfo -> EntityDishesInfo));
                for (OrderedShowDishesListVo vo : dishesList) {
                    vo.setPhotoUrl(dishesMap.get(vo.getDishesId()).getPhotoUrl());
                }
            }

            orderedShowVo.setDishesList(dishesList);

            orderedShowVo.setOrderNo(entityXfRecord.getOrderNo());
            orderedShowVo.setOrderTime(DateUtils.dateToStr(entityXfRecord.getConsTime()));
            orderedShowVo.setMealDate(DateUtils.getStrDate(entityXfRecord.getMealDate(), DateUtils.YYYY_MM_DD));
            orderedShowVo.setMealNo(entityXfRecord.getMealNo());
            if (null != entityXfMealInfos && 0 < entityXfMealInfos.size()) {
                orderedShowVo.setMealName(entityXfMealInfos.get(0).getMealName());
            } else {
                orderedShowVo.setMealName(entityXfRecord.getMealName());
            }
            orderedShowVo.setMerchName(entityXfRecord.getMerchName());
            orderedShowVo.setPointName(entityXfRecord.getPointName());
            orderedShowVo.setDeviceNo(entityXfRecord.getDeviceNo());
            orderedShowVo.setPId(entityXfRecord.getPId().toString());
            orderedShowVo.setPName(entityXfRecord.getPName());
            orderedShowVo.setPCode(entityXfRecord.getPCode());
            orderedShowVo.setReceiptNo(entityXfRecord.getReceiptNo());
            orderedShowVo.setRemark(entityXfRecord.getReserved3());
            orderedShowVo.setPointId(entityXfRecord.getPointId());
            orderedShowVo.setMerchId(entityXfRecord.getMerchId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_1001);
        }
        return ResultUtil.success(orderedShowVo);
    }

    /**
     * 6.6退餐（OrderPage/orderReturn）
     */
    @PostMapping(WxServiceUrl.URL_OrderPageOrderReturn)
    public Result orderReturn(@RequestBody Map<String, Object> map) {
        OrderReturnRequest request = JSON.parseObject(JSON.toJSONString(map), OrderReturnRequest.class);
        Long comId = request.getUserInfo().getComId();

        GetRecordProcessRequest processRequest = new GetRecordProcessRequest();
        processRequest.setCompanyId(comId);
        processRequest.setTradeNo(request.getOrderNo());
        Result result = payHandleClientService.getRecordProcess(processRequest);
        if (200 != result.getCode()) {
            return result;
        }
        EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfRecordProcess.class);

        if (null == entityXfRecordProcess || 0 < entityXfRecordProcess.getIfRefund()  || entityXfRecordProcess.getVerification()==1) {
            return ResultUtil.error(ResultEnum.Err_4136);
        }

        if(ObjectUtil.isNotEmpty(entityXfRecordProcess.getDiscount()) && !entityXfRecordProcess.getDiscount().equals(0L)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("comId",comId);
            jsonObject.put("startTime", DateUtil.formatDateTime(entityXfRecordProcess.getConsTime()));
            jsonObject.put("pCode",entityXfRecordProcess.getPCode());
            jsonObject.put("mealDate",DateUtil.formatDate(entityXfRecordProcess.getMealDate()));
            jsonObject.put("orderBy","id");
//            jsonObject.put("id",entityXfRecordProcess.getId()+1);
            jsonObject.put("page",1);
            jsonObject.put("size",10);
            jsonObject.put("ifRefund",0);
            jsonObject.put("consState","1,3,5");
            Result resultA = this.xfRecodeClientService.getConsumeDetail(jsonObject);
            //不为空，不给退
            JSONObject jsonObjectA = JSON.parseObject(JSON.toJSONString(resultA.getData()));
;
            List<EntityXfRecord> entityXfRecordList = JSON.parseArray(JSON.toJSONString(jsonObjectA.get("list")),EntityXfRecord.class);
            if(ObjectUtil.isNotEmpty(entityXfRecordList) && entityXfRecordList.get(0).getOrderNo().equals(entityXfRecordProcess.getOrderNo()) && entityXfRecordList.size() > 1){
                return ResultUtil.error(ResultEnum.Err_4145);
            }
        }

        ConsTimeConfigOnShowRequest consTimeConfigOnShowRequest =new ConsTimeConfigOnShowRequest();
        consTimeConfigOnShowRequest.setComId(comId);
        consTimeConfigOnShowRequest.setPage(1);
        consTimeConfigOnShowRequest.setSize(50);

        Result result1 = payConfigClientService.GetMealTimeInfo(consTimeConfigOnShowRequest);
        if (result1.getCode() == 200) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result1.getData()));

            List<GetMealTimeDto> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), GetMealTimeDto.class);

            for (GetMealTimeDto mealTimeDto : list) {
                if (mealTimeDto.getMealNo().equals(entityXfRecordProcess.getMealNo())) {
                    long nowLong = new Date().getTime();

                    //餐段时间
                    Date after = null;
                    try {
                        after = DateUtils.getDate(DateUtils.getStrDate(entityXfRecordProcess.getMealDate(), "yyyy-MM-dd") + " " + mealTimeDto.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
                    } catch (ParseException e) {
                        continue;
                    }
                    long afterLong = after.getTime() - (mealTimeDto.getBeforeHour() * 3600000);
                    
                    if (nowLong > afterLong) {
                        return ResultUtil.error(ResultEnum.Err_4139);
                    }
                }
                continue;
            }
        }


        FeeRefundRequest feeRefund = new FeeRefundRequest();
        feeRefund.setCompanyId(comId);
        feeRefund.setFeeItemId(0);
        feeRefund.setPId(0);
        feeRefund.setRefundAmount(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
        feeRefund.setOrigTradeNo(request.getOrderNo());
        feeRefund.setTradeNo(new Date().getTime() + "C" + comId + "P" + entityXfRecordProcess.getPId());
        feeRefund.setCheck(false);
        result = payHandleClientService.paraRefund(feeRefund);

        if (200 != result.getCode()) {
            return result;
        }

        RefundOrderDishesRequest dishesRequest = new RefundOrderDishesRequest();
        dishesRequest.setOrderNo(request.getOrderNo());
        dishesRequest.setComId(comId);
        result = payConfigClientService.refundOrderDishes(dishesRequest);

        return result;
    }
}
